package com.xrz.sxm.aj.entity_tab;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.xrz.sxm.aj.db.DBManager;
import com.xrz.sxm.aj.entity.BingDetail;
import com.xrz.sxm.aj.entity.XueweiEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DBHelps {

	//	private SQLiteDatabase m_SqLiteDatabase;
	private Context m_Context;
	private DbUtils m_DbUtils;

	private DBManager m_DbManager;

	public DBHelps(Context ctx) {
		if (m_DbUtils == null)
			m_DbUtils = DbUtils.create(ctx);
		m_DbUtils.configDebug(true);
		this.m_Context = ctx;
		m_DbManager = new DBManager(ctx);
//		m_SqLiteDatabase = m_DbManager.getDB();
	}


//	public void copy(CopyListener lis) throws Exception{
//		String sql = "select name from sqlite_master where type='table' order by name";
//		Cursor cursor = m_SqLiteDatabase.rawQuery(sql,null);
//		lis.copy(cursor.getCount()-2,0,0,0);
//		int pro = 0;
//		while(cursor.moveToNext()){
//			String tabname = cursor.getString(cursor.getColumnIndex("name"));
//			if(tabname.equals("android_metadata") == false || tabname.equals("sqlite_sequence") == false){
//				getResultByTabname(tabname,lis);
//			}
//			lis.copy(cursor.getCount()-2,pro++,0,0);
//		}
//		cursor.close();
//	}
//
//	private void getResultByTabname(String tabname,CopyListener lis) throws Exception{
//		String strsql = "select * from "+tabname;
//		Class cls = Class.forName("com.xrz.sxm.aj.entity_tab." + tabname);
//		Cursor cursor = m_SqLiteDatabase.rawQuery(strsql, null);
//		int i=0;
//		while(cursor.moveToNext()){
//			m_DbUtils.save(getT(cls, cursor));
//		}
//		cursor.close();
//	}

	public void del(Class cl) {
		try {
			m_DbUtils.deleteAll(cl);
		} catch
				(Exception e) { // TODO: handle exception
		}
	}

	/**
	 * 随机获取15个穴位名字
	 *
	 * @return
	 */
	public List<String> getMathXuewei() {
		try {
			List<String> strs = getAllXuewei();
			if(strs == null || strs.size() == 0)return new ArrayList<>();
			Collections.shuffle(strs);
			if(strs.size() <= 15)return strs;
			return strs.subList(0, 15);
		} catch (Exception e) {
		}
		return new ArrayList<>();
	}
	public List<String> getAllXuewei(){
		try {
			List<Xwmxb> list = m_DbUtils.findAll(Xwmxb.class);
			List<String> strs = new ArrayList<>();
			for(Xwmxb xwmxb : list){
				strs.add(xwmxb.xwmc);
			}
			return strs;
		} catch (Exception e) {
		}
		return null;
	}
	public List<Xwmxb> getPicnameByXueweiName(String xueweiname){
		try{
			List<Xwmxb> list = m_DbUtils.findAll(Selector.from(Xwmxb.class).where("xwmc","=",xueweiname));
			return list;
		}catch(Exception e){
		}
		return null;
	}

	/**
	 * 功能：检测是否升级
	 *
	 * @param sjsj
	 * @return
	 */

	public boolean isUpdate(Sjsj sjsj) {
		try {
			List<Sjsj> list =
					m_DbUtils.findAll(Selector.from(Sjsj.class).where("bmc", "=", sjsj.bmc));
			if (list == null || list.size() == 0) {
				m_DbUtils.save(sjsj);
				return
						true;
			}
			for (Sjsj s : list) {
				if (s.bmc.equals(sjsj.bmc) && s.sjbz ==
						sjsj.sjbz) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			Log.e("----", e.toString());
			return true;
		}
	}

	public void saveSJSJ(Sjsj sjsj) {
		try {
			m_DbUtils.save(sjsj);
		} catch
				(Exception e) {
		}
	}

	/**
	 * 功能：保存
	 *
	 * @param list
	 */
	public void save(List list, SaveListener listener) {
		try {
			for (int i = 0; i < list.size(); i++) {
				m_DbUtils.save(list.get(i));
				listener.save(i + 1, list.size());
			}
		} catch
				(Exception e) {
			Log.e("save", e.toString());
		}
	}

	public interface SaveListener {
		void save(int progress, int totle);
	}

	public interface CopyListener {
		void copy(int allMax, int allProess, int progress, int totle);
	}

	public void updateSjsj(Sjsj entity) {
		try {
			m_DbUtils.update(entity,
					WhereBuilder.b("bmc", "=", entity.bmc), "sjbz");
		} catch (Exception e) {
			Log.e("updateSjsj", e.toString());
		}
	}

	/**
	 * 获取总资讯条数
	 */
	public int GetZiXunNums() {
		try {
			return (int) m_DbUtils.count(Selector.from(Xwzxb.class));
		} catch (Exception e) {
		}
		return 0;

//		String sql = "select * from Xwzxb";
//		Cursor cursor = m_SqLiteDatabase.rawQuery(sql, null);
//		int count = cursor.getCount();
//		cursor.close();
//		return count;
	}

	/**
	 * 资讯列表
	 */
	public List<Xwzxb> getZixunDatas() {
		try {
			return m_DbUtils.findAll(Selector.from(Xwzxb.class));
		} catch
				(Exception e) {
		}
		return null;

//		List<Xwzxb> list = new ArrayList<Xwzxb>();
//		String sql = "select * from Xwzxb";
//		try {
//			list = getTs(Xwzxb.class, sql);
//		} catch (Exception e) {
//		}
//		return list;
	}

	/**
	 * function：根据sql语句获取一个实体类的列表
	 * ModifyDatetime: 2015-3-27 下午01:03:25
	 *
	 * @param <T>
	 * @param cls
	 * @param sql
	 * @return
	 * @throws Exception
	 */
//	private <T> List<T> getTs(Class<T> cls, String sql) throws Exception {
//		List<T> list = new ArrayList<T>();
//		Cursor cursor = m_SqLiteDatabase.rawQuery(sql, null);
//		T t;
//		while (cursor.moveToNext()) {
//			t = getT(cls, cursor);
//			list.add(t);
//		}
//		cursor.close();
//		return list;
//	}

	/**
	 * function：根据cursor获取一个实体类
	 * ModifyDatetime: 2015-3-27 下午01:03:44
	 *
	 * @param <T>
	 * @param cls
	 * @param cursor
	 * @return
	 * @throws Exception
	 */
	private <T> T getT(Class<T> cls, Cursor cursor) throws Exception {
		T ob = cls.newInstance();
		Field[] fields = cls.getFields();
		for (Field field : fields) {
			String name = field.getName();
			field.setAccessible(true);
			String type = field.getGenericType().toString();
			if (type.equals("class java.lang.String")) {
				// String类型
				field.set(ob, cursor.getString(cursor.getColumnIndex(name)));
			} else if (type.equals("class java.lang.Integer") || type.equals("int")) {
				// int类型
				field.set(ob, cursor.getInt(cursor.getColumnIndex(name)));
			}
		}
		return ob;
	}

	/**
	 * 获取典型案例的名字
	 */
	public List<String> getAnLiDatas() {
		List<String> l = new ArrayList<String>();
		try {
			List<Dxalb> list = m_DbUtils.findAll(Selector.from(Dxalb.class));
//			List<Dxalb> list = getTs(Dxalb.class, "select * from Dxalb");
			if (list != null && list.size() != 0) {
				for (Dxalb dxalb : list) {
					l.add(dxalb.albt);
				}
			}
		} catch (Exception e) {
		}
		return l;

	}

	/**
	 * 根据典型案例的病例名获取内容实例
	 */
	public String getAnLicontent(String name) {
		String content = "";
		try {
			List<Dxalb> list = m_DbUtils.findAll(Selector.from(Dxalb.class)
					.where("albt", "=", name));
//			List<Dxalb> list = getTs(Dxalb.class, "select * from Dxalb where albt='" + name + "'");
			if (list != null && list.size() != 0) {
				content = list.get(0).jtnr;
			}
		} catch (Exception e) {
		}
		return content;
	}

	/**
	 * 获取产品的名字和图片
	 */

	public List<Cpmxb> GetChanPinDatas() {
		try {
//			return getTs(Cpmxb.class, "select * from Cpmxb");
			return m_DbUtils.findAll(Selector.from(Cpmxb.class));
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 根据身体部位获取病名列表
	 *
	 * @param buwei
	 * @return
	 */
	public List<String> getBingByBuwei(String buwei) {
		boolean isQuanshen = buwei.equals("全身");
		List<String> l = new ArrayList<String>();
		try {
			List<Stbm> list;
			if (!isQuanshen) {
				list = m_DbUtils.findAll(Selector.from(Stbm.class).where(
						"bwmc", "=", buwei));
//				list = getTs(Stbm.class, "select * from Stbm where bwmc='" + buwei + "'");
			} else {
				list = m_DbUtils.findAll(Selector.from(Stbm.class));
//				list = getTs(Stbm.class, "select * from Stbm");
			}

			if (list != null && list.size() != 0) {
				for (Stbm dxalb : list) {
					l.add(dxalb.bm);
				}
			}
		} catch (Exception e) {
			Log.e("===============", e.toString());
		}
		return l;
	}

	/**
	 * 根据日期分类
	 *
	 * @param list
	 * @return
	 */
	private Map<Integer, List<XueweiEntity>> sort(List<XueweiEntity> list) {
		TreeMap tm = new TreeMap();
		for (int i = 0; i < list.size(); i++) {
			XueweiEntity s = (XueweiEntity) list.get(i);
			if (tm.containsKey(s.ajts)) {//
				ArrayList l11 = (ArrayList) tm.get(s.ajts);
				l11.add(s);
			} else {
				ArrayList tem = new ArrayList();
				tem.add(s);
				tm.put(s.ajts, tem);
			}
		}
		return tm;
	}

	/**
	 * 根据病名获取详细信息
	 *
	 * @param bingName
	 * @return
	 */
	public BingDetail getDetailByBing(String bingName) {
		List<XueweiEntity> entities = new ArrayList<XueweiEntity>();
		BingDetail bingDetail = new BingDetail();
		String ajdm = "";
		try {
//			List<Sbgsb> list = getTs(Sbgsb.class, "select * from Sbgsb where bm='" + bingName + "'");
			List<Sbgsb> list = m_DbUtils.findAll(Selector.from(Sbgsb.class)
					.where("bm", "=", bingName));
			if (list != null && list.size() != 0) {
				Sbgsb sbgsb = list.get(0);
				bingDetail.bm = sbgsb.bm;
				bingDetail.gs = sbgsb.gs;
				bingDetail.byzz = sbgsb.byzz;
				bingDetail.byfx = sbgsb.byfx;
				bingDetail.ajth = sbgsb.ajth;
				bingDetail.tsbz = sbgsb.tsbz;
				bingDetail.sybz = sbgsb.sybz;
				ajdm = sbgsb.ajdm;
//				List<Ajmxb> list2 = getTs(Ajmxb.class, "select * from Ajmxb where ajdm='" + ajdm + "'");
				List<Ajmxb> list2 = m_DbUtils.findAll(Selector
						.from(Ajmxb.class).where("ajdm", "=", ajdm));
				XueweiEntity dbXueweiEntity = null;
				for (Ajmxb ajmxb : list2) {
					int tianshu = ajmxb.ajts;
					String[] wueweis = ajmxb.xwdm.split("、");
					for (String xuewei : wueweis) {
						xuewei = xuewei.replace(" ", "").trim();
						dbXueweiEntity = new XueweiEntity();
						dbXueweiEntity.ajts = tianshu;
//						List<Xwmxb> list3 = getTs(Xwmxb.class, "select * from Xwmxb where xwmc='" + xuewei + "'");
						List<Xwmxb> list3 = m_DbUtils.findAll(Selector.from(
								Xwmxb.class).where("xwmc", "=", xuewei));
						dbXueweiEntity.xwmc = xuewei;
						for (Xwmxb xwmxb : list3) {
							dbXueweiEntity.tmlj = xwmxb.tmlj;
							dbXueweiEntity.ajsj = xwmxb.ajsj;
							dbXueweiEntity.bz = xwmxb.bz;
							dbXueweiEntity.qxms = xwmxb.qxms;
							dbXueweiEntity.zzbz = xwmxb.zzbz;
							dbXueweiEntity.lcyy = xwmxb.lcyy;
							dbXueweiEntity.jldm = xwmxb.jldm;
						}
						entities.add(dbXueweiEntity);
					}
				}
				Map<Integer, List<XueweiEntity>> map = sort(entities);
				bingDetail.quxues = map;
			}
		} catch (Exception e) {
		}
		return bingDetail;
	}

	/**
	 * 根据经络代码获取经络信息
	 *
	 * @param jinguodaima
	 * @return
	 */
	public Jlb getJingluoByDaima(String jinguodaima) {
		Jlb entity = new Jlb();
		try {
//			List<Jlb> list = getTs(Jlb.class, "select * from Jlb where jldm='" + jinguodaima + "'");
			List<Jlb> list = m_DbUtils.findAll(Selector.from(Jlb.class).where(
					"jldm", "=", jinguodaima));
			entity = list.get(0);
		} catch (Exception e) {
		}

		return entity;
	}

	/**
	 * 根据分类名字获取病名
	 *
	 * @param text
	 * @return
	 */
	public List<String> getFenleiByName(String text) {
		List<String> results = new ArrayList<String>();
		try {
//			List<Sbgsb> list = getTs(Sbgsb.class, "select * from Sbgsb where sybz='" + text + "'");
			List<Sbgsb> list = m_DbUtils.findAll(Selector.from(Sbgsb.class)
					.where("sybz", "=", text));
			for (Sbgsb sbgsb : list) {
				results.add(sbgsb.bm);
			}
		} catch (Exception e) {
		}

		return results;
	}

	/**
	 * 根据特殊标记获取病名
	 *
	 * @param teshu
	 * @return
	 */
	public List<String> getFenleiByTeShu(String teshu) {
		List<String> results = new ArrayList<String>();
		try {
//			List<Sbgsb> list = getTs(Sbgsb.class, "select * from Sbgsb where tsbz='" + teshu + "'");
			List<Sbgsb> list = m_DbUtils.findAll(Selector.from(Sbgsb.class)
					.where("tsbz", "like", "%"+teshu+"%"));
			for (Sbgsb sbgsb : list) {
				results.add(sbgsb.bm);
			}
		} catch (Exception e) {
		}

		return results;

	}

	public List<String> search(String key) {
		List<String> results = new ArrayList<String>();
		try {
//			List<Sbgsb> list = getTs(Sbgsb.class, "select * from Sbgsb where bm like '%" + key + "%'");
			List<Sbgsb> list = m_DbUtils.findAll(Selector.from(Sbgsb.class)
					.where("bm", "like", "%" + key + "%"));
			for (Sbgsb sbgsb : list) {
				results.add(sbgsb.bm);
			}
		} catch (Exception e) {
		}

		return results;

	}

	/**
	 * 搜索的获取病名列表
	 */
	public List<String> getKeys() {

		List<String> results = new ArrayList<String>();
		try {
//			List<Sbgsb> list = getTs(Sbgsb.class, "select * from Sbgsb");
			List<Sbgsb> list = m_DbUtils.findAll(Selector.from(Sbgsb.class));
			for (Sbgsb sbgsb : list) {
				results.add(sbgsb.bm);
			}
		} catch (Exception e) {
		}

		return results;

	}

}
